package com.gitee.neuray.security.gateway.config;

import com.gitee.neuray.security.admin.authority.PermissionElementDto;
import com.gitee.neuray.security.auth.common.util.jwt.IJWTInfo;
import com.gitee.neuray.security.common.context.BaseContextHandler;
import com.gitee.neuray.security.common.util.ClientUtil;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 网关日志
 */
@Component
public class GateWayLog {
    public void setCurrentUserInfoAndLog(RequestContext ctx, IJWTInfo user, PermissionElementDto pm) {
        setCurrentUserInfo(ctx,user);
        BaseContextHandler.set("pm", pm);
    }

    public void setCurrentUserInfo(RequestContext ctx, IJWTInfo user) {
        ctx.addZuulRequestHeader("userId", user.getId());
        ctx.addZuulRequestHeader("accout", user.getUniqueName());
        ctx.addZuulRequestHeader("orgCode",user.getOrgCode());
        try {
            ctx.addZuulRequestHeader("orgName",URLEncoder.encode(user.getOrgName(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ctx.addZuulRequestHeader("wxUserId",user.getWxUserId());
        ctx.addZuulRequestHeader("wxAccessToken",user.getWxToken());
        try {
            ctx.addZuulRequestHeader("position",URLEncoder.encode(user.getPosition(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ctx.addZuulRequestHeader("avatar",user.getAvatar());
        try {
            ctx.addZuulRequestHeader("name", URLEncoder.encode(user.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ctx.addZuulRequestHeader("userHost", ClientUtil.getClientIp(ctx.getRequest()));
        BaseContextHandler.set("user", user);
    }
}
